package com.example.demo.loop.comon;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: daiguoqing
 * @Date: 2020-09-04
 * @Time: 15:38
 * @Version: hello-spring-boot 1.0
 */

/**
 * 全局异常表处理类
 */
@ControllerAdvice//组合注解，里面含有Component
public class GlobalDefultExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Object defultExcepitonHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException {
        e.printStackTrace();
        if (e instanceof MyException) {
            //自定义异常
            MyException exception = (MyException) e;
            response.sendRedirect(request.getContextPath()+"/index");
            return exception;
        }
        //系统异常
        return e;
    }
}
